package com.sherry.base;

import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.GeneratedMessage;
import com.qingqing.api.proto.v1.ProtoBufResponse.BaseResponse;
import org.testng.Assert;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by swl on 2021/6/21.
 */
public class ResponseParseUtil {

    public static <T extends GeneratedMessage> T convertToProtoResponse(ByteArrayOutputStream buf, Class<? extends GeneratedMessage> clazz){
        T response = null;
        try {
            Method method = clazz.getMethod("parseFrom",byte[].class);

//            Constructor con =  clazz.getConstructor();
//            T instance  = (T) con.newInstance();

            response = (T) method.invoke(null,buf.toByteArray());
            Map<FieldDescriptor,Object> fields =  response.getAllFields();
            for (FieldDescriptor field: fields.keySet()){
                if (field.getName().equals("response")){
                    BaseResponse baseResponse = (BaseResponse)fields.get(field);
                    switch (baseResponse.getErrorCode()){
                        case 404:{
                            Assert.fail("检查url是否正确，或者当前分支是否正确");
                            break;
                        }case 503:{
                            Assert.fail("服务可能正在部署中...请确认一下");
                            break;
                        }case 500:{
                            Assert.fail("接口抛出异常，请检查");
                            break;
                        }
                    }
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }
}
